interface DesignData {
  baseProductID: string;
  elements: DesignElement[];
  lastModified: number;
}

interface DesignElement {
  id: string;
  position: { x: number; y: number };
  transform: {
    scale: number;
    rotation: number;
  };
}

interface ShopifyConfig {
  shopDomain: string;
  accessToken: string;
}

export const getShopifyProducts = async (config: ShopifyConfig) => {
  const response = await fetch(`https://${config.shopDomain}/admin/api/2024-01/products.json`, {
    headers: {
      'X-Shopify-Access-Token': config.accessToken,
    },
  });
  
  if (!response.ok) {
    throw new Error('Failed to fetch Shopify products');
  }
  
  const data = await response.json();
  return data.products;
};

export const saveDesignToShopify = async (designData: any, config: ShopifyConfig) => {
  const response = await fetch(`https://${config.shopDomain}/admin/api/2024-01/products.json`, {
    method: 'POST',
    headers: {
      'X-Shopify-Access-Token': config.accessToken,
      'Content-Type': 'application/json',
    },
    body: JSON.stringify(designData),
  });

  if (!response.ok) {
    throw new Error('Failed to save design to Shopify');
  }

  return response.json();
};

export const updateShopifyProductImage = async (productId: string, imageId: string, imageData: string, config: ShopifyConfig) => {
  const response = await fetch(`https://${config.shopDomain}/admin/api/2024-01/products/${productId}/images/${imageId}.json`, {
    method: 'PUT',
    headers: {
      'X-Shopify-Access-Token': config.accessToken,
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({
      image: {
        attachment: imageData,
      },
    }),
  });

  if (!response.ok) {
    throw new Error('Failed to update product image');
  }

  return response.json();
};

export class ShopifyService {
  private static instance: ShopifyService;

  private constructor() {}

  static getInstance(): ShopifyService {
    if (!ShopifyService.instance) {
      ShopifyService.instance = new ShopifyService();
    }
    return ShopifyService.instance;
  }
 
} 